# 开发者 ：陈常鸿
# 创建时间 ： 2019/06/01
# 最后修改时间 ： 2019/06/12
# 投资者基类
import os
import sys
import json
from abc import ABC,abstractmethod

from websocket import create_connection

class Invest(ABC):
    @abstractmethod
    def capital(self):
        pass
    
    @abstractmethod
    def buy(self,symbol,volume):
        pass
    
    @abstractmethod
    def sell(self,symbol,volume):
        pass

    @abstractmethod
    def cancel(self):
        pass
    
    @abstractmethod
    def position(self):
        pass
    

class Investor:
    '''
    投资者基类，用户逻辑只需继承这个类
    '''
    def __init__(self):
        # 交易所信息
        self.url=''                      # 模拟交易所地址

        # 用户信息
        self.userId=''                   # 用户的id
        self.cash=0                      # 用户在交易所的现金
        self.position=0                  # 持仓
        self.freeze_pos=0                # 冻结持仓
        self.freeze_cash=0               # 冻结现金
        self.capital=0                   # 总资产

        # 用户模板的变量
        self.ws=None                     # 与交易所的websocket链接
        self.order={}                    # 发单的变量
        self.quote={}                    # 行情变量
    
    def start(self):
        '''初始化用户模板'''
        if not self.url:
            raise KeyError("没有填写交易所地址")

        self.ws=create_connection(self.url)
    
    def stop(self):
        self.ws.close()
    
    def buy(self,symbol,price,volume):
        self.sendOrder(0,symbol,price,volume)
    
    def sell(self,symbol,price,volume):
        self.sendOrder(1,symbol,price,volume)
    
    def cancel(self,symbol):
        '''取消一个品种的订单'''
        self.sendOrder(3,symbol,'','')

    def calcelAll(self):
        self.sendOrder(-1,'','','')
    
    def next(self,data):
        raise NotImplementedError
    
    def orderReturn(self,order_return):
        raise NotImplementedError
    
    def tradeReturn(self,tradeReturn):
        raise NotImplementedError
    
    def errorReturn(self,errorReturn):
        raise NotImplementedError
    
    def sendOrder(self,type_,symbol,price,volume):
        self.order=json.dumps({"userId":self.userId,"type":type_,"symbol":symbol,"price":price,"volume":volume})
        order=json.dumps(self.order)
        self.ws.send(order)
        

class InvestTypeA:
    def __init__(self):
        self.invest_type=''

